import {
  containerCpu,
  containerDisk,
  containerMemory,
  getContainerTcpBackLogRange,
  getNodeDetailCPUUsage,
  getNodeDetailDiskUsageRange,
  getNodeDetailMemoryUsage,
  getPodCpuRange,
  getPodFsRange,
  getPodMemoryRange,
  getPodRestartLine,
  getTopologyCpuUsage,
  getTopologyDiskUsage,
  getTopologyMemoryUsage,
  getWorkloadCpuUsage,
  getWorkloadDiskUsage,
  getWorkloadMemoryUsage,
  namespaceCPUUsage,
  namespaceDiskUsage,
  namespaceMemoryUsage,
} from "@/api/topoNodeDetail";
import { basiclineOption, buildLineSeriesData, multipleLineOptionHandle } from "@/utils/chartOption";
import { formatChartTooltip, formatUnit } from "@/utils/format";
import { cloneDeep, map } from "lodash";
import { watch, ref, onMounted } from "vue";
export default function useLineChart({ node: nodeInfo, queryTime, visible }) {
  const lineParams = ref({});
  const cpuOption = ref(cloneDeep(basiclineOption));
  const memoryOption = ref(cloneDeep(basiclineOption));

  const diskOption = ref(cloneDeep(basiclineOption));
  const restartOption = ref(cloneDeep(basiclineOption));
  const tcpBackLogRange = ref(cloneDeep(basiclineOption))
 //tcp全连接半连接队列区间
 const getTcpArrayRange = (params = lineParams) => {
    getContainerTcpBackLogRange(params).then((res) => {
      const arrData = res.data;
      const tcpBackLogData =
        arrData.length > 0
          ? arrData.map((everyPort) => {
              const { port, pid, graph } = everyPort;
              // const nameList = ['synLen', 'synMax', 'acceptLen', 'acceptMax'];
              const nameList = ["synLen", "acceptLen"];
              const nameZh = ["半连接", "全连接"];
              const tcpBackLog = multipleLineOptionHandle(
                graph,
                nameList,
                "",
                { port: port, pid: pid },
                nameZh
              );
              return tcpBackLog;
            })
          : [multipleLineOptionHandle([], "", "")];

          console.log(tcpBackLogData, 'tcpBackLogRange');

          tcpBackLogRange.value = tcpBackLogData
    });
  };
  // 容器重启次数
  const getPodRestart = (params = lineParams) => {
    getPodRestartLine(params).then((res) => {
      const option = lineOptionHandle(res.data, "重启次数", "");
      restartOption.value = option;
    });
  };

  // 构造节点请求图表数据的参数
  const buildLineParams = () => {
    let params = null;
    const { from, to } = queryTime.value;
    const node = nodeInfo.value;
    const { masterIp } = node;
    const baseParams = {
      from,
      to,
      masterIp,
    };
    switch (node.type) {
      case "namespace": {
        params = {
          ...baseParams,
          namespace: node.name,
        };
        break;
      }
      case "container": {
        params = {
          ...baseParams,
          namespace: node.namespace,
          podName: node.masterName,
          containerName: node.name,
        };
        break;
      }
      case "node":
      case "vm_node": {
        params = {
          ...baseParams,
          singleNodeName: node.name,
          nodeName: node.name,
          nodeIp: node.ip,
        };
        break;
      }
      case "pod": {
        params = {
          ...baseParams,
          namespace: node.namespace,
          pod: node.name,
        };

        break;
      }
      case "workload": {
        params = {
          ...baseParams,
          namespace: node.namespace,
          name: node.name,
          type: node.attributes.workloadType,
        };
        break;
      }
      case "vm_instance": {
        params = {
          ...baseParams,
          namespace: node.namespace,
          name: node.name,
          type: "vm",
        };
        break;
      }
      default:
        break;
    }

    lineParams.value = params;
  };
  /**
   * 折线图数据处理公共方法
   * @param data
   * @param name
   * @param unit
   * @param field
   * @returns
   */
  const lineOptionHandle = (data, name, unit, field = "value") => {
    const options = cloneDeep(basiclineOption);
    options.xAxis[0].data = map(data, "time");
    options.legend.data.push(name);
    options.yAxis[0].axisLabel.formatter = (v) => formatUnit(v, unit);
    options.series.push(buildLineSeriesData(name, _.map(data, field)));
    options.tooltip.formatter = (data) => formatChartTooltip(data, unit);
    return options;
  };
  // 根据图表参数请求对应的CPU图表数据
  const getCPULine = async (params = lineParams) => {
    const node = nodeInfo.value;
    const name = "CPU使用量";
    let option = cloneDeep(basiclineOption);

    switch (node.type) {
      case "namespace": {
        const { data } = await namespaceCPUUsage(params);
        option = lineOptionHandle(data, name, "核", "cpuUsage");
        break;
      }
      case "container": {
        const { data } = await containerCpu(params);
        option = lineOptionHandle(data, name, "核", "usage");
        break;
      }
      case "node":
      case "vm_node": {
        const { data } = await getNodeDetailCPUUsage(params);
        option = lineOptionHandle(data, name, "核", "cpuUserUsage");
        break;
      }
      case "pod": {
        const { data } = await getPodCpuRange(params);
        option = lineOptionHandle(data, name, "核", "cpuUsage");
        break;
      }
      case "workload": {
        const { data } = await getWorkloadCpuUsage(params);
        option = lineOptionHandle(data, "CPU使用量", "核");
        break;
      }
      case "vm_instance": {
        const { data } = await getTopologyCpuUsage(params);
        option = lineOptionHandle(data, "CPU使用量", "核");
        break;
      }
      default:
        break;
    }

    cpuOption.value = option;
  };
  // 根据图表参数请求对应的内存图表数据
  const getMemoryLine = async (params = lineParams) => {
    const node = nodeInfo.value;
    const name = "内存使用量";
    let option = cloneDeep(basiclineOption);
    switch (node.type) {
      case "namespace": {
        const { data } = await namespaceMemoryUsage(params);
        option = lineOptionHandle(data, name, "byteMin", "memoryUsage");
        break;
      }
      case "container": {
        const { data } = await containerMemory(params);
        option = lineOptionHandle(data, name, "byteMin", "usage");
        break;
      }
      case "node":
      case "vm_node": {
        const { data } = await getNodeDetailMemoryUsage(params);
        option = lineOptionHandle(data, name, "byteMin", "memoryUsage");
        break;
      }
      case "pod": {
        const { data } = await getPodMemoryRange(params);
        option = lineOptionHandle(data, name, "byteMin", "memoryUsage");
        break;
      }
      case "workload": {
        const { data } = await getWorkloadMemoryUsage(params);
        option = lineOptionHandle(data, name, "byteMin");
        break;
      }
      case "vm_instance": {
        const { data } = await getTopologyMemoryUsage(params);
        option = lineOptionHandle(data, name, "byteMin");
        break;
      }
      default:
        break;
    }
    memoryOption.value = option;
  };
  // 根据图表参数请求对应的磁盘图表数据
  const getDiskLine = async (params = lineParams) => {
    const node = nodeInfo.value;
    const name = "磁盘使用量";
    let option = cloneDeep(basiclineOption);
    switch (node.type) {
      case "namespace": {
        const { data } = await namespaceDiskUsage(params);
        option = lineOptionHandle(data, name, "byteMin", "fsUsage");
        break;
      }
      case "container": {
        const { data } = await containerDisk(params);
        option = lineOptionHandle(data, name, "byteMin", "usage");
        break;
      }
      case "node":
      case "vm_node": {
        const { data } = await getNodeDetailDiskUsageRange(params);
        data.forEach((item) => {
          item.diskUsage = (item.diskTotal * item.diskTotalRate) / 100;
        });
        option = lineOptionHandle(data, name, "byteMin", "diskUsage");
        break;
      }
      case "pod": {
        const { data } = await getPodFsRange(params);
        option = lineOptionHandle(data, name, "byteMin", "fsUsage");
        break;
      }
      case "workload": {
        const { data } = await getWorkloadDiskUsage(params);
        option = lineOptionHandle(data, name, "byteMin");
        break;
      }
      case "vm_instance": {
        const { data } = await getTopologyDiskUsage(params);
        option = lineOptionHandle(data, name, "byteMin");
        break;
      }
      default:
        break;
    }
    diskOption.value = option;
  };
  watch([visible, nodeInfo, queryTime], ([newVisible, newNode, newTime]) => {
    if (newVisible) {
      console.log("newVisible", newVisible);

      buildLineParams();
    }
  });

  watch(lineParams, (newV) => {
    console.log(newV, "line params");
    getCPULine(newV);
    getMemoryLine(newV);
    getDiskLine(newV);

    if (nodeInfo.value.type === "container") {
      getPodRestart(newV);
      getTcpArrayRange(newV)
    }
  });
  // onMounted(() => {
  //   buildLineParams();
  // });
  return {
    cpuOption,
    memoryOption,
    diskOption,
    lineParams,
    tcpBackLogRange,
    restartOption,
    getCPULine,
    getMemoryLine,
    getDiskLine,
    getPodRestart,
  };
}
